<!--
 * @Author: xiaodong 565071984@qq.com
 * @Date: 2022-05-08 19:52:05
 * @LastEditors: xiaodong 565071984@qq.com
 * @LastEditTime: 2022-05-17 23:26:47
 * @FilePath: /小票/src/views/accountManagement/userManagement/components/UserManagementEdit.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="600px"
    :append-to-body="true"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item
        :label="$t('accountManage.orderType') /*订单类型*/"
        prop="iphone"
      >
        <!-- <el-button @click="handleEdit('', 'deviceSelect')">选择</el-button> -->
        <el-input
          v-model.trim="form.editTypeName"
          autocomplete="off"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="$t('accountManage.buyLength') /*购买时长*/"
        prop="iphone"
      >
        <el-input-number
          v-model="form.buyLength"
          :min="1"
          :max="100"
          :label="$t('accountManage.buyLength') /*购买时长*/"
          @change="handleChange"
        ></el-input-number>
        <span class="num-tip">{{ $t('accountManage.month') /*月*/ }}</span>
      </el-form-item>
      <el-form-item
        :label="$t('accountManage.accountType') /*账号类型*/"
        prop="accountType"
        :required="false"
      >
        <el-input
          v-model.trim="form.accountType"
          autocomplete="off"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="$t('accountManage.chargingMode') /*收费模式*/"
        prop="chargingMode"
        :required="false"
      >
        <!-- <el-input
          v-model.trim="form.chargingMode"
          autocomplete="off"
        ></el-input> -->
        <el-radio-group v-model="radio">
          <el-radio
            v-for="(item, index) in radioArray"
            :key="index"
            :label="item.key"
          >
            {{ item.name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="isNewBuy"
        :label="$t('accountManage.buyNumber') /*购买数量*/"
        prop="number"
        :required="false"
      >
        <el-input v-model.trim="form.number" autocomplete="off" disabled>
          <template slot="append">
            {{ $t('accountManage.per') /*个*/ }}
          </template>
        </el-input>
        <!-- <span class="num-tip">个</span> -->
      </el-form-item>
      <el-form-item
        :label="
          isNewBuy
            ? $t('accountManage.buyAccount') /*购买账号*/
            : $t('accountManage.nextBuyAccount') /*续费账号*/
        "
        prop="iphone"
      >
        <el-button @click="handleEdit('', 'deviceSelect')">
          {{ $t('accountManage.select') /*选择*/ }}
        </el-button>
      </el-form-item>
      <!-- <el-form-item
        :label="$t('accountManage.iftekAccount') /*续费账号*/"
        prop="iphone"
      >
        <el-button @click="handleEdit('', 'deviceBuy')">
          {{ $t('accountManage.select') /*选择*/ }}
        </el-button>
      </el-form-item> -->
      <el-form-item label="">
        <!-- :type="tag.type" -->
        <el-tag
          v-for="tag in form.tags"
          :key="tag.name"
          closable
          @close="onClose(tag)"
        >
          {{ tag.name }}
        </el-tag>
      </el-form-item>
      <el-form-item
        :label="$t('accountManage.orderRemark') /*订单备注*/"
        prop="orderMark"
        :required="false"
      >
        <el-input
          v-model.trim="form.orderMark"
          autocomplete="off"
          type="textarea"
        ></el-input>
      </el-form-item>

      <!-- <el-form-item label="设备" prop="iphone">
        <el-button @click="handleEdit('', 'deviceSelect')">
          {{ $t('accountManage.select') /*选择*/ }}
        </el-button>
      </el-form-item> -->

      <el-form-item
        v-if="role_flag === 1"
        :label="$t('accountManage.agentAccountNumber') /*代理商账号*/"
        prop="agentValue"
      >
        <el-select
          v-model="agentValue"
          :placeholder="
            $t('accountManage.pleaseSelAgentAccountNumber') /*请选择代理商*/
          "
          @change="onChangeAgent"
        >
          <el-option
            v-for="item in agentList"
            :key="item.user_id"
            :label="item.username"
            :value="item.user_id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="权限" prop="permissions">
        <el-checkbox-group v-model="form.permissions">
          <el-checkbox label="admin"></el-checkbox>
          <el-checkbox label="editor"></el-checkbox>
        </el-checkbox-group>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ $t('common.cancel') /*取消*/ }}</el-button>
      <el-button type="primary" @click="save">
        {{ $t('common.sure') /*确 定*/ }}
      </el-button>
    </div>
    <!-- 选择账号列表 -->
    <device-select
      ref="deviceSelect"
      :tanant-list="isNewBuy ? tanantList : tanantListXuFei"
      :mody-type="modyType"
      @set-account="setAccount"
    />
    <device-buy
      ref="deviceBuy"
      :tanant-list="tanantList"
      @fetch-data="fetchDataBuy"
    />
    <order-detail ref="orderDetail" @fetch-data="fetchData" />
  </el-dialog>
</template>

<script>
  import {
    buyTenatAccount,
    getAgentList,
    getCanBuyTanantList,
    getCanXfTanantList,
  } from '@/api/agents.js'
  import DeviceBuy from '@/views/accountManagement/userManagement/components/deviceBuy.vue'
  import OrderDetail from '@/views/accountManagement/userManagement/components/orderDetail.vue'
  import DeviceSelect from '@/views/dataStatistics/userManagement/components/deviceSelect.vue'
  import { mapState } from 'vuex'
  export default {
    name: 'UserManagementEdit',
    components: { DeviceSelect, DeviceBuy, OrderDetail },
    data() {
      return {
        options: [
          {
            value: '选项1',
            label: '黄金糕',
          },
        ],
        agentValue: '',
        tanantList: [],
        radioArray: [
          { name: `${this.$t('accountManage.solPer')}` /*按个*/, key: 0 },
          { name: `${this.$t('accountManage.solPackage')}` /*按套餐*/, key: 1 },
        ],
        radio: 0,
        // tags: [
        //   { name: '标签一', type: '' },

        // ],
        modyType: '租户',
        agentList: [], //新购
        tanantListXuFei: [], //续费
        form: {
          buyLength: 1,
          editType: '',
          editTypeName: '',
          number: 1,
          tags: [],
          orderMark: '',
          // chargingMode: 0,
          // chargingModeName: '',
        },
        rules: {
          username: [
            { required: true, trigger: 'blur', message: '请输入用户名' },
          ],
          password: [
            { required: true, trigger: 'blur', message: '请输入密码' },
          ],
          email: [{ required: true, trigger: 'blur', message: '请输入邮箱' }],
          permissions: [
            { required: true, trigger: 'blur', message: '请选择权限' },
          ],
        },
        title: '',
        dialogFormVisible: false,
        isNewBuy: true,
        refshData: '',
      }
    },
    computed: {
      ...mapState({
        role_flag: (state) => state.user?.userinfo?.role_flag,
        userinfo: (state) => state.user?.userinfo,
      }),
    },
    created() {
      this.fetchDataBuy()
      // console.log(this.userinfo, '用户账户信息')
      if (this.role_flag === 1) {
        //如果是管理员
        this.getAgentListFunc()
      }
    },

    methods: {
      async getAgentListFunc() {
        const params = { user_id: this.userinfo.user_id }
        const res = await getAgentList(params)
        this.agentList = res?.data || []
        console.log(res, '代理商列表')
      },
      onChangeAgent(value) {
        // console.log(value)
        this.form.agent_user_id = value
      },
      onClose(tag) {
        this.form.tags = this.form.tags.filter(
          (item) => item.da_id !== tag.da_id
        )
        console.log(this.form.tags, '新购站好')
      },
      setAccount(selAccounts) {
        this.form.tags = selAccounts
      },
      async getCanBuyTanantListFunc() {
        const res = await getCanBuyTanantList()
        const data = res?.data
        console.log(res, '获取数据 - 租户账号列表- 新购')
        this.tanantList = data?.data || []
      },
      async getCanXfTanantListFunc() {
        const res = await getCanXfTanantList()
        const data = res?.data
        console.log(res, '获取数据 - 租户账号列表 -续费')
        this.tanantListXuFei = data?.data || []
      },
      handleChange(value) {
        console.log(value)
      },
      handleEdit(row, type = 'edit', from) {
        if (row.id) {
          this.$refs[type].showEdit(row, this.isNewBuy)
        } else {
          this.$refs[type].showEdit('', this.isNewBuy, from)
        }
      },
      async fetchDataBuy() {
        //租户账号
        this.listLoading = true
        // const { data, totalCount } = userData || (await getList(this.queryForm))
        this.getCanBuyTanantListFunc()
        this.getCanXfTanantListFunc()
        // this.total = total
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 300)
      },
      async fetchData() {
        this.listLoading = true
        // const { data, totalCount } = userData || (await getList(this.queryForm))
        // this.getCanBuyTanantListFunc()
        // this.getCanXfTanantListFunc()
        // console.log(data, '获取数据 - 123')
        // this.list = data?.data || []
        // this.total = totalCount
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 300)
      },
      showEdit(row, editType, refshData) {
        // if (!row) {
        //   this.title = `${this.$t('common.newBug')}` /*新购*/
        // } else {

        //   // this.form = Object.assign({}, row)
        // }

        this.title =
          editType === 0
            ? `${this.$t('common.newBug')}` /*新购*/
            : `${this.$t('common.renewal')}` /*续费*/
        this.dialogFormVisible = true
        // modyType
        this.form = Object.assign(
          {},
          { ...this.form },
          {
            editTypeName:
              editType === 0
                ? `${this.$t('common.newBug')}` /*新购*/
                : `${this.$t('common.renewal')}` /*续费*/,
          },
          { editType },
          {
            accountType:
              this.modyType === '租户'
                ? `${this.$t('accountManage.tenantAccountNumber')}` /*租户账号*/
                : `${this.$t('accountManage.deviceAccount')}` /*设备账号*/,
          }
          // {
          //   chargingMode: 0,
          //   chargingModeName: `${this.$t('accountManage.solPer')}` /*按个*/,
          // }
        )

        this.isNewBuy = editType === 0 ? true : false
        if (this.modyType === '租户') {
          this.radioArray = [
            { name: `${this.$t('accountManage.solPer')}` /*按个*/, key: 0 },
          ]
        }
        this.refshData = refshData
      },
      close() {
        this.form.tags = []
        this.$refs['form'].resetFields()
        // this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        const that = this
        console.log(this.form, '新增租户')
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (!that.form.tags || that.form.tags?.length === 0) {
              that.$message.error(`${that.$t('accountManage.pleaseAccount')}`)
              /*请选择账号*/
              return
            }
            if (!this.form.agent_user_id) {
              that.$message.error(
                `${that.$t('accountManage.pleaseSelAgentAccountNumber')}`
              )
              /*请选择代理商*/
              return
            }
            const params = {
              aclist: that.form.tags.map((item) => item.da_id),
              order_type: that.isNewBuy ? 1 : 2,
              order_time: that.form.buyLength,
              buy_type: !that.radio ? 1 : 2,
              num_acount: that.form.number,
              order_mark: that.form.orderMark,
              agent_user_id: this.form.agent_user_id,
            }
            console.log('新购', params)
            const res = await buyTenatAccount(params)
            if (res.code === 0) {
              let message = this.isNewBuy
                ? `${that.$t('accountManage.buySuccess')}`
                : `${that.$t('accountManage.xuSuccess')}`
              that.$message.success(message)
              // this.refshData && this.refshData() //刷新操作
            }
            // this.handleEdit('', 'orderDetail', that.form)
            // const { msg } = await doEdit(this.form)
            // this.$baseMessage(msg, 'success')
            // this.$emit('fetch-data')
            that.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
<style scoped>
  .num-tip {
    margin: 0 0 0 12px;
  }
</style>
